﻿function bindOnScroll(id, callback)
{
	var element;
	
	if(typeof(id) == "string")
		element = $(id);
	if(element == null)
		return;

	if(element.addEventListener) // firefox (w3c compliant way)
	{
		element.addEventListener('DOMMouseScroll', callback, false);
	}
	else if(element.attachEvent) // ie FFFFFFUUUUUUUUUUUU
	{
		element.attachEvent("onmousewheel", callback);
	}
}

function unbindOnScroll(id, callback)
{
	var element;
	
	if(typeof(id) == "string")
		element = $(element);
	if(element == null)
		return;

	if(element.removeEventListener) // firefox (w3c compliant way)
	{
		element.removeEventListener('DOMMouseScroll', callback, false);
	}
	else if(element.detachEvent) // ie FFFFFFUUUUUUUUUUUU
	{
		element.detachEvent("onmousewheel", callback);
	}
}

function makeScroll(id, startPos, rowHeight)
{
	var elem = $(id);
	
	if (isIE)
	{
		bindOnScroll(id, function(e) {
			var delta = -getDelta(e);
			
			elem.scrollTop += delta * rowHeight;
		});
		return;
	}
	
	bindOnScroll(id, function(e) {
		var delta = getDelta(e);
		
		var currTop = cssTop();
		var currHeight = cssHeight();
		
		var newTop = currTop + delta * rowHeight;
		
		newTop = min(0, newTop); // top не должен быть больше ноля, чтобы верхний край не опускался слишком низко
		newTop = max(-currHeight + 36, newTop); // и не должен быть меньше -currHeight + 36, чтобы нижний край не поднимался слишком высоко
		elem.style.top = newTop + "px";
	});
	
	function getDelta(e)
	{
		var event = (e ? e : window.event);
		
		if (event.detail)
		{
			return event.detail / (-3);
		}
		
		return event.wheelDelta / 120;
	}
	
	function cssTop()
	{
		var top = elem.style.top;
		var len = top.length;
		top = top.substr(0, len - 2);
		return Number(top);
	}
	
	function cssHeight()
	{
		var height = elem.style.height;
		var len = height.length;
		height = height.substr(0, len - 2);
		return Number(height);
	}
}